#include "stm32f10x.h"                  // Device header
#include "Serial.h"

uint8_t TimeSetFlashFlag;
uint8_t Serial_TxFlag = 0;
uint8_t Serial_Count = 0;


void Timer_Init(void)
{
	Serial_Init();
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
	
	TIM_InternalClockConfig(TIM4);
	/*溢出频率 = TIM2-7频率 / (ARR+1) / (PSC+1)*/
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period = 10000 - 1;//ARR,10khz/10k=1hz
	TIM_TimeBaseInitStructure.TIM_Prescaler = 7200 - 1;//PSC, 72Mhz/7200=10khz
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStructure);
	/**/
	TIM_ClearITPendingBit(TIM4, TIM_IT_Update);//手动清除因刚初始化完就进入中断产生的标志位
	/**/
	TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	NVIC_InitTypeDef NVIC_InitStucture;
	NVIC_InitStucture.NVIC_IRQChannel = TIM4_IRQn;
	NVIC_InitStucture.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStucture.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitStucture.NVIC_IRQChannelSubPriority = 2;
	NVIC_Init(&NVIC_InitStucture);
	
	TIM_Cmd(TIM4, ENABLE);
}

void TIM4_IRQHandler(void)
{
	if(TIM_GetITStatus(TIM4, TIM_IT_Update) == SET)
	{
		TimeSetFlashFlag =! TimeSetFlashFlag;
		TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
		if(Serial_TxFlag == 1)
		{
			Serial_Count++;
			if(Serial_Count == 10)
			{
				Serial_Printf("\r\n你妈叫你回家吃药！");
				Serial_Count = 0;
			}
		}
		else
		{
			Serial_Count = 0;
		}
	}
}
